#include "devfs.h"


void devfs_init()
{
	devfs_nodes = NULL;
	devfs_root = (vfs_node_t *) malloc(sizeof(vfs_node_t));
	devfs_root->readdir = devfs_readdir;
	devfs_root->finddir = devfs_finddir;
	strcpy(devfs_root->name, "devfs\0");
	
	vfs_add_fs(devfs_root);	
}



/*
 * Se un nodo e' gia' presente da' 1
 */
uint8_t devfs_check_node(char *name)
{
	return inode_list_check(&devfs_nodes, name);
}



/*
 * Elimina un nodo
 */	
uint8_t devfs_dl_node(char *name)
{
	return inode_list_del(&devfs_nodes, name);
}

/*
 * Crea un nodo per il device
 */
vfs_node_t *devfs_mk_node(char *name, uint32_t type)
{
	if(devfs_check_node(name) != 0) return (vfs_node_t *) NULL;
	
	//char *a = (char *) malloc(sizeof(char)*VFS_NODE_NAME_LEN);
	vfs_node_t *dev = (vfs_node_t *) malloc(sizeof(vfs_node_t));
	strcpy(dev->name, name);
	//strcpy(a, name);
	strcat(dev->name, "\0");
	//dev->name[0] = name[0];
	dev->type = type;
	
	inode_list_add(&devfs_nodes, dev);
	
	//printf("\ndevfs '%d' '%s'  '%s' \n",dev,devfs_nodes->name,name);

	return (vfs_node_t *) dev;
}



/*
 * Ottiene il nome del nodo x, restituisce nome e dimensione del nome
 * non si cura della cartella, in quando in ogni posto sia il devfs, ha
 * sempre gli stessi file
 */
uint8_t devfs_readdir(vfs_node_t *node, char *name, uint32_t x)
{
	//printf("devfs readdir dir '%s' node number %d\n",node->name, x);
	
	uint32_t y = 0;
	vfs_node_t *t = devfs_nodes;
	
	
	while(t != NULL)
	{
		if(y == x)
		{
			strcpy(name, t->name);
			//printf("dev %s\n", t->name);
			return 1;
		}
		t = t->next;
		y++;
	}
	return 0;	
}


/*
 * Ottiene il nodo chiamato name
 */
vfs_node_t *devfs_finddir(vfs_node_t *node, char *name)
{
	//printf("devfs finddir %s\n",name);
	vfs_node_t *t = devfs_nodes;
	
	while(t != NULL)
	{
		//printf("%s\n", t->name);
		if(strcmp(t->name, name) == 0) return t;
		t = t->next;
	}
	return 0;
}
